package com.working.libcommon.exts

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.util.Base64
import java.io.ByteArrayOutputStream
import java.io.IOException


fun Bitmap.toBase64(): String? {
    var result: String? = null
    var baos: ByteArrayOutputStream? = null
    try {
        baos = ByteArrayOutputStream()
        this.compress(Bitmap.CompressFormat.JPEG, 100, baos)
        baos.flush()
        baos.close()

        result = Base64.encodeToString(baos.toByteArray(), Base64.NO_WRAP)
    } catch (ex: IOException) {
        ex.printStackTrace()
    } finally {
        try {
            baos?.let {
                it.flush()
                it.close()
            }
        } catch (ex: IOException) {
            ex.printStackTrace()
        }
    }
    return result
}

fun String.toBitmap(): Bitmap? {
    val bytes: ByteArray = Base64.decode(this, Base64.DEFAULT)
    return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
}